/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package net.dntuan.simplexmlbundle.servlet;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.Date;

import javax.servlet.ServletException;

import net.dntuan.simplexmlbundle.internal.DatePattern;
import net.dntuan.simplexmlbundle.internal.HttpDateTransformer;
import net.dntuan.simplexmlbundle.model.RSS;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Properties;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.Service;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.servlets.SlingAllMethodsServlet;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;
import org.simpleframework.xml.transform.RegistryMatcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 
 * @author tuandn
 */
@Component(immediate = true, metatype = false, description = "example sling servlet")
@Service(value = javax.servlet.Servlet.class)
@Properties(value = { @Property(name = "sling.servlet.methods", value = { "GET" }),
        @Property(name = "sling.servlet.extensions", value = { "html" }),
        @Property(name = "sling.servlet.resourceTypes", value = "exampleservlet") })
@SuppressWarnings("serial")
public class ExampleServlet extends SlingAllMethodsServlet {

    private static final Logger LOGGER = LoggerFactory.getLogger(ExampleServlet.class);

    @Override
    protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException,
            IOException {
        try {
            RegistryMatcher matcher = new RegistryMatcher();
            matcher.bind(Date.class, new HttpDateTransformer(DatePattern.HTTP_PATTERN));
            Serializer serializer = new Persister(matcher);

            URL teamTalkRss = new URL("http://www.teamtalk.com/rss/1765");
            BufferedReader in = new BufferedReader(new InputStreamReader(teamTalkRss.openStream()));
            RSS ex = serializer.read(RSS.class, in, false);

            Gson gson = new GsonBuilder().setPrettyPrinting().create();
            response.getWriter().println(gson.toJson(ex));
        } catch (Exception ex1) {
            LOGGER.error(ex1.getMessage(), ex1);
        }
    }
}
